package com.db.bankapp.network.client;

import java.io.*;
import java.net.Socket;

/**
 * Created by Java Student on 8/22/2014.
 */
public class BankNetworkClient {
    private final String host;
    private final int port;

    public BankNetworkClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws IllegalAccessException {
        if (args.length != 2) {
            throw new IllegalAccessException("Both host and port must be set!");
        }
        BankNetworkClient client = new BankNetworkClient(args[0], Integer.parseInt(args[1]));
        client.run();
    }

    public void run() {
        try (Socket socket = new Socket(host, port);
             BufferedWriter sockOut = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
             BufferedReader sockIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));
             BufferedWriter consoleOut = new BufferedWriter(new OutputStreamWriter(System.out))) {
            while(true) {
                String message = consoleIn.readLine();
                if ("q".equals(message) || "quit".equals(message) || "exit".equals(message)) {
                    System.exit(0);
                }

                sockOut.write(message);
                sockOut.newLine();
                sockOut.flush();

                String response = sockIn.readLine();
                consoleOut.write(response);
                consoleOut.newLine();
                consoleOut.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
